package com.lil.shiro.service.impl;

import com.lil.shiro.exception.BusinessException;
import com.lil.shiro.model.User;
import com.lil.shiro.result.ApiResponse;
import com.lil.shiro.result.ResultCode;
import com.lil.shiro.service.LoginService;
import com.lil.shiro.service.UserService;
import com.lil.shiro.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService sysUserService;

    @Override
    public ApiResponse login(String userId, String password) {
        // 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();
        String msg = "";
        // 3、将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userId, password);

        ApiResponse apiResponse = new ApiResponse();

        // 4、认证
        try {

            log.info("---token---" + token.getPassword() + "------");
            currentUser.login(token);// 传到MyAuthorizingRealm类中的方法进行认证
//            currentUser.
//            Session session = currentUser.getSession();
//            session.setAttribute("userId", userId);
//            loginResult.setLogin(true);

            User userInfo = sysUserService.findUserInfo(userId);
            apiResponse.setData(convertFromModel(userInfo));
            apiResponse.setResultCode(ResultCode.SUCCESS);
            return apiResponse;
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            msg = "UnknownAccountException -- > 账号不存在：";
            apiResponse.setResultCode(ResultCode.USERNAME_NULL);
        } catch (IncorrectCredentialsException e) {
            msg = "IncorrectCredentialsException -- > 密码不正确：";
            apiResponse.setResultCode(ResultCode.PASSWORD_ERROR);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            apiResponse.setResultCode(ResultCode.USERNAME_ERROR);
            msg = "用户验证失败";
        }

        return apiResponse;
    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
    //将核心模型转化为UI可用模型
    private UserVo convertFromModel(User userModel) {
        if (null == userModel) {
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userModel, userVo);
        log.info("userVo ： " + userVo.toString());
        return userVo;
    }
}
